package io.github.novaframe.lock;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Melvin
 * @since 2018-01-07 2:06
 */
public class MapSimpleLock {

    private static final Map<String, Lock> lockMap = Maps.newConcurrentMap();

    public static Lock getLock(String lockName) {
        return lockMap.get(lockName);
    }

    /**
     * 这种方式不行，多个线程第一次获取锁，锁为空时可能会同时新建锁导致出现线程同步问题
     * @param lockName
     * @return
     */
    public static Lock getLockNew(String lockName) {
        Lock lock = lockMap.get(lockName);
        if (lock == null) {
            lock = new ReentrantLock();
            lockMap.put(lockName, lock);
        }

        return lock;
    }

    public static void initLock(String lockName) {
        lockMap.put(lockName, new ReentrantLock());
    }
}
